<?php
class MediaController extends Controller
{
	public $layout = 'main';
	private $thumb_sizes = array('120x120');
	private $thumb_path = '/thumbs';
	private $allowedFileExtension = 'jpg,jpeg,png,gif,swf,flv,mp4';

	public function actionIndex()
	{
		$intPage 		= (int)Yii::app()->request->getParam('page', 1);
		$intRowsPerPage = (int)Yii::app()->request->getParam('rpp', MIN_ROWS_PER_PAGE);
		$intSortType 	= Yii::app()->request->getParam('sort',-1);
		
		$strKeyword		= Yii::app()->request->getParam('keyword', null);
		$strFileTypes	= Yii::app()->request->getParam('filetype', null);
		$strFolder  = Yii::app()->request->getParam('folder', null);
		$strCreatedDateFrom  = Yii::app()->request->getParam('dfrom', null);
		$strCreatedDateTo  = Yii::app()->request->getParam('dto', null);
		
		$strFileExts = null;
		if($strFileTypes == 'image'){
			$strFileExts = "jpg, jpeg, png, gif";
		}
		if($strFileTypes == 'video'){
			$strFileExts = "flv, mp4, ogg, ogv, avi, mpeg, mov, wmv, mkv, 3gp";
		}
		
		$args = array(
			'sort'=>$intSortType, 
			'keyword'=>'%'.$strKeyword.'%', 
			'file_type'=>$strFileExts, 
			'created_from' => !empty($strCreatedDateFrom)?date('Y-m-d', strtotime($strCreatedDateFrom)):null,
			'created_to' => !empty($strCreatedDateTo)?date('Y-m-d', strtotime($strCreatedDateTo)):null,
			'folder'=>$strFolder
		);
		
		$arrMedia = Media::getInstance()->getList($args, $intPage, $intRowsPerPage);
		$intTotalRows = isset($arrMedia[0]['total_rows'])?$arrMedia[0]['total_rows']:0;
		
		//pagination
		$objPages=new CPagination($intTotalRows);
		$objPages->setCurrentPage($intPage-1);
		$objPages->setPageSize($intRowsPerPage);
		
		if(Yii::app()->request->isAjaxRequest && Yii::app()->request->isPostRequest){
			$strMessage = '';
			$pagination = array(
				'pageSize' => $objPages->getPageSize() /*rpp*/,
				'pageCount' => $objPages->getPageCount() /*total pages*/,			
				'currentPage' => $objPages->getCurrentPage(),
				'pageRange' => 5,
				'itemCount' => $objPages->getItemCount() /*total items*/
			);
			echo json_encode(array('list'=>$arrMedia, 'pagination'=>$pagination, 'message'=>$strMessage)); die;
		}
		else {
			$this->render('index', array(
				'arrMedia' => $arrMedia,
				'objPages' => $objPages,
				'args' => array(
									'sort'=>$intSortType, 
									'keyword'=>$strKeyword, 
									'file_type'=>$strFileTypes, 
									'folder'=>$strFolder,
									'created_from' => $strCreatedDateFrom,
									'created_to' => $strCreatedDateTo,
								)
			));
		}
	}
	
	public function actionPopup()
	{
		$this->renderPartial('popup', array());
	}
	
	public function actionForm(){
		$this->render('form', array(
		));
	}
	
	public function actionUpload(){
		$redirect = Yii::app()->request->getParam('redirect', 1);
		if(Yii::app()->request->isPostRequest){
			try{
				$strFolder = Yii::app()->request->getParam('folder', null);
				
				//Rearrange uploaded files
				$files = FileTransfer::rearrangeGlobalFilesArray($_FILES['media']);
				foreach($files as $file){
					/*skip no uploaded file error*/
					if($file['error'] == UPLOAD_ERR_NO_FILE) continue;
					/*start uploading...*/
					$objFileTransfer = new FileTransfer(UPLOADS_DIR, array('prefixPath'=>'src/'.date('Y').'/'.date('md'), 'allowedFileExtension'=>$this->allowedFileExtension));
					$arrFileInfo = $objFileTransfer->upload($file);
					if($arrFileInfo !== false){
						/*prepare data for inserting db*/
						$args = array(
							'media_title' => $arrFileInfo['filename'],
							'media_file' => $arrFileInfo['path'],
							'media_file_size' => $arrFileInfo['size'],
							'media_file_extension' => $arrFileInfo['extension'],
							'media_src' => 1,
							'media_folder' => $strFolder,
							'media_creator_id' => Yii::app()->admin->id
						);
						/*insert into database*/				
						$intResult = Media::getInstance()->insert($args);
						/*create thumbs if this is an image*/
						if($intResult > 0){
							$this->thumb($arrFileInfo);
						}
					}
				}
			} catch(Exception $ex) {
				o($ex->getMessage());
				//$this->_helper->getHelper('FlashMessenger')->addMessage(json_encode(array('type'=>'error', 'msg'=>$ex->getMessage())));
			}
		}
		/*TODO: redirect to finished page*/
		/*if($redirect){
			header('Location: '.LINK_ADMINCP_MEDIA.'/form'); die;
			//$this->_redirect(LINK_ADMINCP_MEDIA);
		}*/
		if(Yii::app()->request->isAjaxRequest && Yii::app()->request->isPostRequest){
			echo $intResult;
		}
		header('Location: '.LINK_ADMINCP_MEDIA.'/form'); die;
	}

	public function actionDownload(){
		$strFolder = Yii::app()->request->getParam('folder', null);
		$url = Yii::app()->request->getParam('url', null);
		if (filter_var($url, FILTER_VALIDATE_URL) === false) {
			die("{$url} is not a valid URL");
		}
		
		if(Yii::app()->request->isPostRequest){
			
			
			$objFileTransfer = new FileTransfer(UPLOADS_DIR, UPLOADS_DIR, array('prefixPath'=>'src/'.date('Y').'/'.date('md'), 'allowedFileExtension'=>$this->allowedFileExtension));
			$arrFileInfo = $objFileTransfer->downloadFromUrl($url);
			
			if($arrFileInfo !== false){
				/*prepare data for inserting db*/
				$args = array(
					'media_title' => $arrFileInfo['filename'],
					'media_file' => $arrFileInfo['path'],
					'media_file_size' => $arrFileInfo['size'],
					'media_file_extension' => $arrFileInfo['extension'],
					'media_src' => 1,
					'media_folder' => $strFolder,
					'media_creator_id' => Yii::app()->admin->id
				);
				/*insert into database*/				
				$intResult = Media::getInstance()->insert($args);
				/*create thumbs if this is an image*/
				if($intResult > 0){
					$this->thumb($arrFileInfo);
				}
			}
		}
		if(Yii::app()->request->isAjaxRequest && Yii::app()->request->isPostRequest){
			echo $intResult;
		}
		header('Location: '.LINK_ADMINCP_MEDIA.'/form'); die;
	}
	
	public function actionDelete(){
		$intId = Yii::app()->request->getParam('id', null);
		if(!empty($intId)){
			/* get media info */
			$media = Media::getInstance()->get($intId);
			if(!empty($media)){
				$strFilePath = UPLOADS_DIR.'/'.$media['media_file'];
				/*if file is image then delete thumbs*/
				if(in_array($media['media_file_extension'], array('jpg', 'jpeg', 'png', 'gif'))){
					$strThumbPath = str_replace('/src/', '/thumbs/120x120/', $strFilePath);	
					if(is_file($strThumbPath)) @unlink($strThumbPath);
				}
				/*delete source*/
				if(is_file($strFilePath)) @unlink($strFilePath);
			}
			/* delete from db */		
			$result = Media::getInstance()->delete($intId);
		}
		header('Location: '.LINK_ADMINCP_MEDIA);	
	}
	
	public function thumb($arrFileInfo){
		try{
			if(!empty($arrFileInfo['extension']) && in_array($arrFileInfo['extension'], array('jpg', 'jpeg', 'png', 'gif'))){
				$strFilePath = UPLOADS_DIR.'/'.$arrFileInfo['path'];
				if(is_file($strFilePath)){
					require_once('PHPThumb/PHPThumb.php');
					require_once('PHPThumb/GD.php');
					//compress source
					$thumb = new PHPThumb\GD($strFilePath);
					$thumb->resize(960, 720);
					$thumb->save($strFilePath);
					//create thumbs
					$strThumbPath = str_replace('/src/', '/thumbs/120x120/', $strFilePath);
					@mkdir(pathinfo($strThumbPath, PATHINFO_DIRNAME), 0755, true);								
					$thumb = new PHPThumb\GD($strFilePath);
					$thumb->resize(120, 120);
					$thumb->save($strThumbPath);
				} else {
					throw new Exception('Source file is unavailable!');	
				}
			}
		} catch(Excetpion $ex){
			throw new Exception($ex->getMessage());
		}
	}
}